#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/5 14:31
# @Author : luhongxuan
# @Site :
# @File : auth.py
# @Software: PyCharm

import uuid

from django.db import models


class BaseModelManager(models.Manager):
    '''地址模型管理器类'''

    # 1.改变原有查询的结果集:all() 实现软删除
    def all(self):
        model_list = super().all()  # QuerySet
        model_list = model_list.filter(is_delete=False)
        return model_list

    def filter(self, *args, **kwargs):
        model_list = super().filter(*args, **kwargs)  # QuerySet
        model_list = model_list.filter(is_delete=False)
        return model_list

    def delete(self):
        self.update(is_delete=True)


class BaseModel(models.Model):
    # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间", null=True, blank=True)
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间", null=True, blank=True)
    order = models.IntegerField(default=1000, verbose_name='排序列', null=True, blank=True)

    is_delete = models.BooleanField(default=False, max_length=20, null=True)

    objects = BaseModelManager()

    class Meta:
        abstract = True


class ModelMixin(object):
    __slots__ = ()

    def to_dict(self, excludes: tuple = None, selects: tuple = None) -> dict:
        if not hasattr(self, '_meta'):
            raise TypeError('<%r> does not a django.db.models.Model object.' % self)
        elif selects:
            return {f: getattr(self, f) for f in selects}
        elif excludes:
            return {f.attname: getattr(self, f.attname) for f in self._meta.fields if f.attname not in excludes}
        else:
            return {f.attname: getattr(self, f.attname) for f in self._meta.fields}
